package com.snail.clouds.storage.providers.tianyi_tv;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

import java.util.HashMap;
import java.util.Map;
import java.util.List;
import java.util.ArrayList;

/**
 * 天翼TV API封装类
 * 基于Go语言实现，严格验证逻辑
 */
public class CloudsApi {
    
    private Map<String, Object> tokenInfo;
    private String familyId;
    private boolean isFamily = false;
    
    public CloudsApi() {
        this.tokenInfo = new HashMap<>();
    }
    
    /**
     * 获取二维码登录UUID
     * 参考Go实现：getQrCodeUUID
     */
    public Map<String, Object> getQrCodeUUID() throws Exception {
        try {
            String url = SignatureUtils.API_URL + "/family/manage/getQrCodeUUID.action";
            
            // 生成签名头
            Map<String, String> headers = SignatureUtils.getAppKeySignatureHeader(url, "GET");
            
            Map<String, Object> params = SignatureUtils.getClientSuffix();
            
            String response = HttpUtils.get(url, headers, params);
            JSONObject responseJson = HttpUtils.parseJsonResponse(response);
            
            if (HttpUtils.hasError(responseJson)) {
                throw new Exception("获取二维码UUID失败: " + HttpUtils.getErrorMessage(responseJson));
            }
            
            Map<String, Object> result = new HashMap<>();
            result.put("uuid", responseJson.getStr("uuid"));
            return result;
            
        } catch (Exception e) {
            throw new Exception("获取二维码UUID失败: " + e.getMessage(), e);
        }
    }
    
    /**
     * 检查二维码登录结果
     * 参考Go实现：checkQrCodeLoginResult
     */
    public Map<String, Object> checkQrCodeLoginResult(String uuid) throws Exception {
        try {
            String url = SignatureUtils.API_URL + "/family/manage/qrcodeLoginResult.action";
            
            // 生成签名头
            Map<String, String> headers = SignatureUtils.getAppKeySignatureHeader(url, "GET");
            
            Map<String, Object> params = SignatureUtils.getClientSuffix();
            params.put("uuid", uuid);
            
            String response = HttpUtils.get(url, headers, params);
            JSONObject responseJson = HttpUtils.parseJsonResponse(response);
            
            // 检查是否是等待状态
            if (responseJson.containsKey("res_code") && "QrCodeRollLoginFail".equals(responseJson.getStr("res_code"))) {
                return null; // 返回null表示还在等待
            }
            
            if (HttpUtils.hasError(responseJson)) {
                throw new Exception("检查二维码登录结果失败: " + HttpUtils.getErrorMessage(responseJson));
            }
            
            // 检查是否包含accessToken（成功登录）
            String accessToken = responseJson.getStr("accessToken");
            if (responseJson.containsKey("accessToken") && StrUtil.isNotBlank(accessToken)) {
                Map<String, Object> result = new HashMap<>();
                result.put("accessToken", accessToken);
                result.put("expiresIn", responseJson.getLong("expiresIn"));
                return result;
            }
            
            // 如果accessToken为空字符串，视为等待状态，与Go实现保持一致
            if (responseJson.containsKey("accessToken") && StrUtil.isEmpty(accessToken)) {
                return null; // 返回null表示还在等待
            }
            
            return null; // 还在等待
            
        } catch (Exception e) {
            throw new Exception("检查二维码登录结果失败: " + e.getMessage(), e);
        }
    }
    
    /**
     * 使用E189AccessToken登录获取SessionKey和SessionSecret
     * 参考Go实现：loginFamilyMerge
     */
    public Map<String, Object> loginFamilyMerge(String e189AccessToken) throws Exception {
        try {
            String url = SignatureUtils.API_URL + "/family/manage/loginFamilyMerge.action";
            
            // 生成签名头
            Map<String, String> headers = SignatureUtils.getAppKeySignatureHeader(url, "GET");
            
            Map<String, Object> params = SignatureUtils.getClientSuffix();
            params.put("e189AccessToken", e189AccessToken);
            
            String response = HttpUtils.get(url, headers, params);
            JSONObject responseJson = HttpUtils.parseJsonResponse(response);
            
            if (HttpUtils.hasError(responseJson)) {
                throw new Exception("登录合并失败: " + HttpUtils.getErrorMessage(responseJson));
            }
            
            // 保存token信息
            this.tokenInfo.put("sessionKey", responseJson.getStr("sessionKey"));
            this.tokenInfo.put("sessionSecret", responseJson.getStr("sessionSecret"));
            this.tokenInfo.put("familySessionKey", responseJson.getStr("familySessionKey"));
            this.tokenInfo.put("familySessionSecret", responseJson.getStr("familySessionSecret"));
            this.tokenInfo.put("loginName", responseJson.getStr("loginName"));
            this.tokenInfo.put("accessToken", e189AccessToken);
            this.tokenInfo.put("refreshToken", responseJson.getStr("refreshToken"));
            
            return this.tokenInfo;
            
        } catch (Exception e) {
            throw new Exception("登录合并失败: " + e.getMessage(), e);
        }
    }
    
    /**
     * 刷新会话
     * 参考Go实现：refreshSession
     */
    public boolean refreshSession() throws Exception {
        try {
            if (!tokenInfo.containsKey("accessToken")) {
                return false;
            }
            
            String url = SignatureUtils.API_URL + "/family/manage/loginFamilyMerge.action";
            
            // 生成签名头
            Map<String, String> headers = SignatureUtils.getAppKeySignatureHeader(url, "GET");
            
            Map<String, Object> params = SignatureUtils.getClientSuffix();
            params.put("e189AccessToken", tokenInfo.get("accessToken"));
            
            String response = HttpUtils.get(url, headers, params);
            JSONObject responseJson = HttpUtils.parseJsonResponse(response);
            
            if (HttpUtils.hasError(responseJson)) {
                return false;
            }
            
            // 更新token信息
            this.tokenInfo.put("sessionKey", responseJson.getStr("sessionKey"));
            this.tokenInfo.put("sessionSecret", responseJson.getStr("sessionSecret"));
            this.tokenInfo.put("familySessionKey", responseJson.getStr("familySessionKey"));
            this.tokenInfo.put("familySessionSecret", responseJson.getStr("familySessionSecret"));
            
            return true;
            
        } catch (Exception e) {
            return false;
        }
    }
    
    /**
     * 获取用户信息
     * 参考Go实现：getUserInfo
     */
    public Map<String, Object> getUserInfo() throws Exception {
        try {
            String url = SignatureUtils.API_URL + "/getUserInfo.action";
            
            // 生成签名头
            Map<String, String> headers = SignatureUtils.getSignatureHeader(url, "GET",
                    (String) tokenInfo.get("sessionKey"),
                    (String) tokenInfo.get("sessionSecret"));
            
            Map<String, Object> params = SignatureUtils.getClientSuffix();
            
            String response = HttpUtils.get(url, headers, params);
            JSONObject responseJson = HttpUtils.parseJsonResponse(response);
            
            if (HttpUtils.hasError(responseJson)) {
                throw new Exception("获取用户信息失败: " + HttpUtils.getErrorMessage(responseJson));
            }
            
            Map<String, Object> result = new HashMap<>();
            result.put("loginName", responseJson.getStr("loginName"));
            
            // 如果用户信息中没有容量信息，尝试获取容量信息
            if (!responseJson.containsKey("cloudCapacityInfo") && !responseJson.containsKey("familyCapacityInfo")) {
                try {
                    Map<String, Object> capacityInfo = getCapacityInfo();
                    // 合并容量信息到用户信息中
                    if (capacityInfo != null && capacityInfo.containsKey("cloudCapacityInfo")) {
                        result.put("cloudCapacityInfo", capacityInfo.get("cloudCapacityInfo"));
                    } else if (capacityInfo != null && capacityInfo.containsKey("familyCapacityInfo")) {
                        result.put("familyCapacityInfo", capacityInfo.get("familyCapacityInfo"));
                    }
                } catch (Exception e) {
                    // 忽略容量信息获取失败
                }
            } else {
                if (responseJson.containsKey("cloudCapacityInfo")) {
                    result.put("cloudCapacityInfo", responseJson.get("cloudCapacityInfo"));
                }
                if (responseJson.containsKey("familyCapacityInfo")) {
                    result.put("familyCapacityInfo", responseJson.get("familyCapacityInfo"));
                }
            }
            
            return result;
            
        } catch (Exception e) {
            throw new Exception("获取用户信息失败: " + e.getMessage(), e);
        }
    }
    
    /**
     * 获取文件列表
     * 参考Go实现：getFiles
     */
    public List<Map<String, Object>> getFiles(String folderId) throws Exception {
        try {
            String baseUrl = SignatureUtils.API_URL + "/listFiles.action";
            if (isFamily) {
                baseUrl = SignatureUtils.API_URL + "/family/file/listFiles.action";
            }
            
            // 生成签名头
            String sessionKey = isFamily ? (String) tokenInfo.get("familySessionKey") : (String) tokenInfo.get("sessionKey");
            String sessionSecret = isFamily ? (String) tokenInfo.get("familySessionSecret") : (String) tokenInfo.get("sessionSecret");
            Map<String, String> headers = SignatureUtils.getSignatureHeader(baseUrl, "GET", sessionKey, sessionSecret);
            
            List<Map<String, Object>> files = new ArrayList<>();
            
            // 实现分页逻辑，与Go实现一致
            for (int pageNum = 1; ; pageNum++) {
                Map<String, Object> params = SignatureUtils.getClientSuffix();
                params.put("folderId", folderId);
                params.put("fileType", "0");
                params.put("mediaAttr", "0");
                params.put("iconOption", "5");
                params.put("pageNum", String.valueOf(pageNum));
                params.put("pageSize", "130");
                
                if (isFamily) {
                    params.put("familyId", familyId);
                    params.put("orderBy", "1"); // 按文件名排序
                    params.put("descending", "false");
                } else {
                    params.put("recursive", "0");
                    params.put("orderBy", "1"); // 按文件名排序
                    params.put("descending", "false");
                }
                
                String response = HttpUtils.get(baseUrl, headers, params);
                JSONObject responseJson = HttpUtils.parseJsonResponse(response);
                
                if (HttpUtils.hasError(responseJson)) {
                    throw new Exception("获取文件列表失败: " + HttpUtils.getErrorMessage(responseJson));
                }
                
                // 检查是否还有文件
                if (responseJson.containsKey("fileListAO")) {
                    JSONObject fileListAO = responseJson.getJSONObject("fileListAO");
                    int count = fileListAO.getInt("count");
                    
                    // 获取完毕跳出
                    if (count == 0) {
                        break;
                    }
                    
                    // 处理文件夹
                    if (fileListAO.containsKey("folderList")) {
                        List<JSONObject> folderList = fileListAO.getBeanList("folderList", JSONObject.class);
                        for (JSONObject folder : folderList) {
                            Map<String, Object> folderMap = new HashMap<>();
                            folderMap.put("id", folder.getStr("id"));
                            folderMap.put("name", folder.getStr("name"));
                            folderMap.put("parentId", folder.getStr("parentId"));
                            folderMap.put("createDate", folder.getStr("createDate"));
                            folderMap.put("lastOpTime", folder.getStr("lastOpTime"));
                            folderMap.put("isFolder", true);
                            files.add(folderMap);
                        }
                    }
                    
                    // 处理文件
                    if (fileListAO.containsKey("fileList")) {
                        List<JSONObject> fileList = fileListAO.getBeanList("fileList", JSONObject.class);
                        for (JSONObject file : fileList) {
                            Map<String, Object> fileMap = new HashMap<>();
                            fileMap.put("id", file.getStr("id"));
                            fileMap.put("name", file.getStr("name"));
                            fileMap.put("size", file.getLong("size"));
                            fileMap.put("md5", file.getStr("md5"));
                            fileMap.put("createDate", file.getStr("createDate"));
                            fileMap.put("lastOpTime", file.getStr("lastOpTime"));
                            fileMap.put("isFolder", false);
                            
                            // 处理图标信息
                            if (file.containsKey("icon")) {
                                JSONObject icon = file.getJSONObject("icon");
                                fileMap.put("smallUrl", icon.getStr("smallUrl"));
                                fileMap.put("largeUrl", icon.getStr("largeUrl"));
                            }
                            
                            files.add(fileMap);
                        }
                    }
                }
            }
            
            return files;
            
        } catch (Exception e) {
            throw new Exception("获取文件列表失败: " + e.getMessage(), e);
        }
    }
    
    /**
     * 创建文件夹
     * 参考Go实现：createFolder
     */
    public Map<String, Object> createFolder(String name, String parentId) throws Exception {
        try {
            String url = SignatureUtils.API_URL + "/createFolder.action";
            if (isFamily) {
                url = SignatureUtils.API_URL + "/family/file/createFolder.action";
            }
            
            // 生成签名头
            String sessionKey = isFamily ? (String) tokenInfo.get("familySessionKey") : (String) tokenInfo.get("sessionKey");
            String sessionSecret = isFamily ? (String) tokenInfo.get("familySessionSecret") : (String) tokenInfo.get("sessionSecret");
            Map<String, String> headers = SignatureUtils.getSignatureHeader(url, "POST", sessionKey, sessionSecret);
            
            Map<String, Object> params = SignatureUtils.getClientSuffix();
            params.put("folderName", name);
            params.put("relativePath", "");
            
            if (isFamily) {
                params.put("familyId", familyId);
                params.put("parentId", parentId);
            } else {
                params.put("parentFolderId", parentId);
            }
            
            String response = HttpUtils.post(url, headers, params);
            JSONObject responseJson = HttpUtils.parseJsonResponse(response);
            
            if (HttpUtils.hasError(responseJson)) {
                throw new Exception("创建文件夹失败: " + HttpUtils.getErrorMessage(responseJson));
            }
            
            Map<String, Object> result = new HashMap<>();
            result.put("id", responseJson.getStr("id"));
            result.put("name", responseJson.getStr("name"));
            result.put("parentId", responseJson.getStr("parentId"));
            result.put("createDate", responseJson.getStr("createDate"));
            result.put("lastOpTime", responseJson.getStr("lastOpTime"));
            
            return result;
            
        } catch (Exception e) {
            throw new Exception("创建文件夹失败: " + e.getMessage(), e);
        }
    }
    
    /**
     * 获取文件下载链接
     * 参考Go实现：getDownloadUrl
     */
    public String getDownloadUrl(String fileId) throws Exception {
        try {
            String url = SignatureUtils.API_URL + "/getFileDownloadUrl.action";
            if (isFamily) {
                url = SignatureUtils.API_URL + "/family/file/getFileDownloadUrl.action";
            }
            
            // 生成签名头
            String sessionKey = isFamily ? (String) tokenInfo.get("familySessionKey") : (String) tokenInfo.get("sessionKey");
            String sessionSecret = isFamily ? (String) tokenInfo.get("familySessionSecret") : (String) tokenInfo.get("sessionSecret");
            Map<String, String> headers = SignatureUtils.getSignatureHeader(url, "GET", sessionKey, sessionSecret);
            
            Map<String, Object> params = SignatureUtils.getClientSuffix();
            params.put("fileId", fileId);
            
            if (isFamily) {
                params.put("familyId", familyId);
            } else {
                params.put("dt", "3");
                params.put("flag", "1");
            }
            
            String response = HttpUtils.get(url, headers, params);
            JSONObject responseJson = HttpUtils.parseJsonResponse(response);
            
            if (HttpUtils.hasError(responseJson)) {
                throw new Exception("获取下载链接失败: " + HttpUtils.getErrorMessage(responseJson));
            }
            
            String downloadUrl = responseJson.getStr("fileDownloadUrl");
            
            // 处理重定向获取真实链接
            if (StrUtil.isNotBlank(downloadUrl)) {
                downloadUrl = downloadUrl.replace("&", "&").replace("http://", "https://");
            }
            
            return downloadUrl;
            
        } catch (Exception e) {
            throw new Exception("获取下载链接失败: " + e.getMessage(), e);
        }
    }
    
    /**
     * 获取容量信息
     * 参考Go实现：getCapacityInfo
     */
    public Map<String, Object> getCapacityInfo() throws Exception {
        try {
            String url = SignatureUtils.API_URL + "/portal/getUserSizeInfo.action";
            
            // 生成签名头
            Map<String, String> headers = SignatureUtils.getSignatureHeader(url, "GET",
                    (String) tokenInfo.get("sessionKey"),
                    (String) tokenInfo.get("sessionSecret"));
            
            Map<String, Object> params = SignatureUtils.getClientSuffix();
            
            String response = HttpUtils.get(url, headers, params);
            JSONObject responseJson = HttpUtils.parseJsonResponse(response);
            
            if (HttpUtils.hasError(responseJson)) {
                throw new Exception("获取容量信息失败: " + HttpUtils.getErrorMessage(responseJson));
            }
            
            Map<String, Object> result = new HashMap<>();
            if (responseJson.containsKey("cloudCapacityInfo")) {
                result.put("cloudCapacityInfo", responseJson.get("cloudCapacityInfo"));
            }
            if (responseJson.containsKey("familyCapacityInfo")) {
                result.put("familyCapacityInfo", responseJson.get("familyCapacityInfo"));
            }
            
            return result;
            
        } catch (Exception e) {
            throw new Exception("获取容量信息失败: " + e.getMessage(), e);
        }
    }
    
    /**
     * 保活会话
     * 参考Go实现：keepAlive
     */
    public boolean keepAlive() {
        try {
            String url = SignatureUtils.API_URL + "/keepUserSession.action";
            
            Map<String, Object> params = SignatureUtils.getClientSuffix();
            
            String response = HttpUtils.get(url, null, params);
            JSONObject responseJson = HttpUtils.parseJsonResponse(response);
            
            return !HttpUtils.hasError(responseJson);
            
        } catch (Exception e) {
            return false;
        }
    }
    
    /**
     * 创建批量任务
     * 参考Go实现：CreateBatchTask
     */
    public Map<String, Object> createBatchTask(String taskType, String familyId, String targetFolderId,
                                              Map<String, String> other, List<Map<String, Object>> taskInfos) throws Exception {
        try {
            String url = SignatureUtils.API_URL + "/batch/createBatchTask.action";
            
            // 生成签名头
            String sessionKey = isFamily ? (String) tokenInfo.get("familySessionKey") : (String) tokenInfo.get("sessionKey");
            String sessionSecret = isFamily ? (String) tokenInfo.get("familySessionSecret") : (String) tokenInfo.get("sessionSecret");
            Map<String, String> headers = SignatureUtils.getSignatureHeader(url, "POST", sessionKey, sessionSecret);
            
            // 分离查询参数和表单参数，与Go实现保持一致
            Map<String, Object> queryParams = SignatureUtils.getClientSuffix();
            
            Map<String, Object> formParams = new HashMap<>();
            formParams.put("type", taskType);
            formParams.put("taskInfos", JSONUtil.toJsonStr(taskInfos));
            
            if (targetFolderId != null && !targetFolderId.isEmpty()) {
                formParams.put("targetFolderId", targetFolderId);
            }
            
            if (familyId != null && !familyId.isEmpty()) {
                formParams.put("familyId", familyId);
            }
            
            // 添加其他参数
            if (other != null && !other.isEmpty()) {
                for (Map.Entry<String, String> entry : other.entrySet()) {
                    formParams.put(entry.getKey(), entry.getValue());
                }
            }
            
            String response = HttpUtils.postWithSeparateParams(url, headers, queryParams, formParams);
            JSONObject responseJson = HttpUtils.parseJsonResponse(response);
            
            if (HttpUtils.hasError(responseJson)) {
                throw new Exception("创建批量任务失败: " + HttpUtils.getErrorMessage(responseJson));
            }
            
            Map<String, Object> result = new HashMap<>();
            result.put("taskId", responseJson.getStr("taskId"));
            return result;
            
        } catch (Exception e) {
            throw new Exception("创建批量任务失败: " + e.getMessage(), e);
        }
    }
    
    /**
     * 检查批量任务状态
     * 参考Go实现：CheckBatchTask
     */
    public Map<String, Object> checkBatchTask(String taskType, String taskId) throws Exception {
        try {
            String url = SignatureUtils.API_URL + "/batch/checkBatchTask.action";
            
            // 生成签名头
            String sessionKey = isFamily ? (String) tokenInfo.get("familySessionKey") : (String) tokenInfo.get("sessionKey");
            String sessionSecret = isFamily ? (String) tokenInfo.get("familySessionSecret") : (String) tokenInfo.get("sessionSecret");
            Map<String, String> headers = SignatureUtils.getSignatureHeader(url, "POST", sessionKey, sessionSecret);
            
            Map<String, Object> params = SignatureUtils.getClientSuffix();
            params.put("type", taskType);
            params.put("taskId", taskId);
            
            String response = HttpUtils.post(url, headers, params);
            JSONObject responseJson = HttpUtils.parseJsonResponse(response);
            
            if (HttpUtils.hasError(responseJson)) {
                throw new Exception("检查批量任务状态失败: " + HttpUtils.getErrorMessage(responseJson));
            }
            
            Map<String, Object> result = new HashMap<>();
            result.put("taskStatus", responseJson.getInt("taskStatus"));
            result.put("process", responseJson.getInt("process"));
            result.put("successedCount", responseJson.getInt("successedCount"));
            result.put("failedCount", responseJson.getInt("failedCount"));
            
            return result;
            
        } catch (Exception e) {
            throw new Exception("检查批量任务状态失败: " + e.getMessage(), e);
        }
    }
    
    /**
     * 重命名文件
     * 参考Go实现：renameFile
     */
    public Map<String, Object> renameFile(String fileId, String newName, boolean isFolder) throws Exception {
        try {
            String url = SignatureUtils.API_URL;
            String method = "POST";
            
            if (isFamily) {
                url += "/family/file";
            }
            
            if (isFolder) {
                url += "/renameFolder.action";
            } else {
                url += "/renameFile.action";
            }
            
            // 生成签名头
            String sessionKey = isFamily ? (String) tokenInfo.get("familySessionKey") : (String) tokenInfo.get("sessionKey");
            String sessionSecret = isFamily ? (String) tokenInfo.get("familySessionSecret") : (String) tokenInfo.get("sessionSecret");
            Map<String, String> headers = SignatureUtils.getSignatureHeader(url, method, sessionKey, sessionSecret);
            
            Map<String, Object> params = SignatureUtils.getClientSuffix();
            
            if (isFolder) {
                params.put("folderId", fileId);
                params.put("destFolderName", newName);
            } else {
                params.put("fileId", fileId);
                params.put("destFileName", newName);
            }
            
            if (isFamily) {
                params.put("familyId", familyId);
            }
            
            String response;
            if (isFamily && isFolder) {
                // 家庭云文件夹重命名使用GET方法
                response = HttpUtils.get(url, headers, params);
            } else {
                response = HttpUtils.post(url, headers, params);
            }
            
            JSONObject responseJson = HttpUtils.parseJsonResponse(response);
            
            if (HttpUtils.hasError(responseJson)) {
                throw new Exception("重命名失败: " + HttpUtils.getErrorMessage(responseJson));
            }
            
            Map<String, Object> result = new HashMap<>();
            result.put("id", responseJson.getStr("id"));
            result.put("name", responseJson.getStr("name"));
            result.put("createDate", responseJson.getStr("createDate"));
            result.put("lastOpTime", responseJson.getStr("lastOpTime"));
            
            if (!isFolder && responseJson.containsKey("icon")) {
                JSONObject icon = responseJson.getJSONObject("icon");
                result.put("smallUrl", icon.getStr("smallUrl"));
                result.put("largeUrl", icon.getStr("largeUrl"));
            }
            
            return result;
            
        } catch (Exception e) {
            throw new Exception("重命名失败: " + e.getMessage(), e);
        }
    }
    
    /**
     * 创建上传文件会话
     * 参考Go实现：OldUploadCreate
     */
    public Map<String, Object> createUploadFile(String parentId, String fileMd5,
                                            String fileName, String fileSize) throws Exception {
        try {
            String url = SignatureUtils.API_URL + "/createUploadFile.action";
            if (isFamily) {
                url = SignatureUtils.API_URL + "/family/file/createFamilyFile.action";
            }
            
            // 生成签名头
            String sessionKey = isFamily ? (String) tokenInfo.get("familySessionKey") : (String) tokenInfo.get("sessionKey");
            String sessionSecret = isFamily ? (String) tokenInfo.get("familySessionSecret") : (String) tokenInfo.get("sessionSecret");
            Map<String, String> headers = SignatureUtils.getSignatureHeader(url, "POST", sessionKey, sessionSecret);
            
            // 分离查询参数和表单参数，与Go实现保持一致
            Map<String, Object> queryParams = SignatureUtils.getClientSuffix();
            
            Map<String, Object> formParams = new HashMap<>();
            
            if (isFamily) {
                // 家庭云使用查询参数
                queryParams.put("familyId", familyId);
                queryParams.put("parentId", parentId);
                queryParams.put("fileMd5", fileMd5);
                queryParams.put("fileName", fileName);
                queryParams.put("fileSize", fileSize);
                queryParams.put("resumePolicy", "1");
            } else {
                // 个人云使用表单参数
                formParams.put("parentFolderId", parentId);
                formParams.put("fileName", fileName);
                formParams.put("size", fileSize);
                formParams.put("md5", fileMd5);
                formParams.put("opertype", "3");
                formParams.put("flag", "1");
                formParams.put("resumePolicy", "1");
                formParams.put("isLog", "0");
            }
            
            String response = HttpUtils.postWithSeparateParams(url, headers, queryParams, formParams);
            JSONObject responseJson = HttpUtils.parseJsonResponse(response);
            
            if (HttpUtils.hasError(responseJson)) {
                throw new Exception("创建上传文件会话失败: " + HttpUtils.getErrorMessage(responseJson));
            }
            
            Map<String, Object> result = new HashMap<>();
            result.put("uploadFileId", responseJson.getLong("uploadFileId"));
            result.put("fileUploadUrl", responseJson.getStr("fileUploadUrl"));
            result.put("fileCommitUrl", responseJson.getStr("fileCommitUrl"));
            result.put("fileDataExists", responseJson.getInt("fileDataExists"));
            
            return result;
            
        } catch (Exception e) {
            throw new Exception("创建上传文件会话失败: " + e.getMessage(), e);
        }
    }
    
    /**
     * 获取上传文件状态
     * 参考Go实现：获取上传状态
     */
    public Map<String, Object> getUploadFileStatus(long uploadFileId) throws Exception {
        try {
            String url = SignatureUtils.API_URL + "/getUploadFileStatus.action";
            if (isFamily) {
                url = SignatureUtils.API_URL + "/family/file/getFamilyFileStatus.action";
            }
            
            // 生成签名头
            String sessionKey = isFamily ? (String) tokenInfo.get("familySessionKey") : (String) tokenInfo.get("sessionKey");
            String sessionSecret = isFamily ? (String) tokenInfo.get("familySessionSecret") : (String) tokenInfo.get("sessionSecret");
            Map<String, String> headers = SignatureUtils.getSignatureHeader(url, "GET", sessionKey, sessionSecret);
            
            Map<String, Object> params = SignatureUtils.getClientSuffix();
            params.put("uploadFileId", uploadFileId);
            params.put("resumePolicy", "1");
            
            if (isFamily) {
                params.put("familyId", familyId);
            }
            
            String response = HttpUtils.get(url, headers, params);
            JSONObject responseJson = HttpUtils.parseJsonResponse(response);
            
            if (HttpUtils.hasError(responseJson)) {
                throw new Exception("获取上传文件状态失败: " + HttpUtils.getErrorMessage(responseJson));
            }
            
            Map<String, Object> result = new HashMap<>();
            result.put("uploadFileId", responseJson.getLong("uploadFileId"));
            result.put("fileUploadUrl", responseJson.getStr("fileUploadUrl"));
            result.put("fileCommitUrl", responseJson.getStr("fileCommitUrl"));
            result.put("fileDataExists", responseJson.getInt("fileDataExists"));
            result.put("dataSize", responseJson.getLong("dataSize"));
            result.put("size", responseJson.getLong("size"));
            
            return result;
            
        } catch (Exception e) {
            throw new Exception("获取上传文件状态失败: " + e.getMessage(), e);
        }
    }
    
    /**
     * 提交上传文件
     * 参考Go实现：OldUploadCommit
     */
    public Map<String, Object> commitUploadFile(String fileCommitUrl, long uploadFileId, boolean overwrite) throws Exception {
        try {
            // 生成签名头
            String sessionKey = isFamily ? (String) tokenInfo.get("familySessionKey") : (String) tokenInfo.get("sessionKey");
            String sessionSecret = isFamily ? (String) tokenInfo.get("familySessionSecret") : (String) tokenInfo.get("sessionSecret");
            Map<String, String> headers = SignatureUtils.getSignatureHeader(fileCommitUrl, "POST", sessionKey, sessionSecret);
            
            Map<String, Object> queryParams = SignatureUtils.getClientSuffix();
            Map<String, Object> formParams = new HashMap<>();
            
            if (isFamily) {
                // 家庭云使用请求头传递参数，与Go实现一致
                headers.put("ResumePolicy", "1");
                headers.put("UploadFileId", String.valueOf(uploadFileId));
                headers.put("FamilyId", familyId);
            } else {
                // 个人云使用表单参数
                formParams.put("opertype", overwrite ? "3" : "1");
                formParams.put("resumePolicy", "1");
                formParams.put("uploadFileId", uploadFileId);
                formParams.put("isLog", "0");
            }
            
            String response = HttpUtils.postWithSeparateParams(fileCommitUrl, headers, queryParams, formParams);
            JSONObject responseJson = HttpUtils.parseJsonResponse(response);
            
            if (HttpUtils.hasError(responseJson)) {
                throw new Exception("提交上传文件失败: " + HttpUtils.getErrorMessage(responseJson));
            }
            
            Map<String, Object> result = new HashMap<>();
            
            if (isFamily) {
                // 家庭云返回JSON格式
                if (responseJson.containsKey("file")) {
                    JSONObject file = responseJson.getJSONObject("file");
                    result.put("id", file.getStr("id"));
                    result.put("name", file.getStr("fileName"));
                    result.put("size", file.getLong("fileSize"));
                    result.put("md5", file.getStr("fileMd5"));
                    result.put("createDate", file.getStr("createDate"));
                }
            } else {
                // 个人云返回XML格式，这里简化处理
                result.put("id", responseJson.getStr("id"));
                result.put("name", responseJson.getStr("name"));
                result.put("size", responseJson.getLong("size"));
                result.put("md5", responseJson.getStr("md5"));
                result.put("createDate", responseJson.getStr("createDate"));
            }
            
            return result;
            
        } catch (Exception e) {
            throw new Exception("提交上传文件失败: " + e.getMessage(), e);
        }
    }
    
    // Getters and Setters
    public Map<String, Object> getTokenInfo() {
        return tokenInfo;
    }
    
    public void setTokenInfo(Map<String, Object> tokenInfo) {
        this.tokenInfo = tokenInfo;
    }
    
    public String getFamilyId() {
        return familyId;
    }
    
    public void setFamilyId(String familyId) {
        this.familyId = familyId;
    }
    
    public boolean isFamily() {
        return isFamily;
    }
    
    public void setFamily(boolean family) {
        isFamily = family;
    }

    /**
     * 获取冲突的任务信息
     * 参考Go实现：GetConflictTaskInfo
     */
    public Map<String, Object> getConflictTaskInfo(String taskType, String taskId) throws Exception {
        try {
            String url = SignatureUtils.API_URL + "/batch/getConflictTaskInfo.action";
            
            // 生成签名头
            String sessionKey = isFamily ? (String) tokenInfo.get("familySessionKey") : (String) tokenInfo.get("sessionKey");
            String sessionSecret = isFamily ? (String) tokenInfo.get("familySessionSecret") : (String) tokenInfo.get("sessionSecret");
            Map<String, String> headers = SignatureUtils.getSignatureHeader(url, "POST", sessionKey, sessionSecret);
            
            Map<String, Object> params = SignatureUtils.getClientSuffix();
            params.put("type", taskType);
            params.put("taskId", taskId);
            
            String response = HttpUtils.post(url, headers, params);
            JSONObject responseJson = HttpUtils.parseJsonResponse(response);
            
            if (HttpUtils.hasError(responseJson)) {
                throw new Exception("获取冲突任务信息失败: " + HttpUtils.getErrorMessage(responseJson));
            }
            
            Map<String, Object> result = new HashMap<>();
            result.put("sessionKey", responseJson.getStr("sessionKey"));
            result.put("targetFolderId", responseJson.getStr("targetFolderId"));
            result.put("taskId", responseJson.getStr("taskId"));
            result.put("taskType", responseJson.getInt("taskType"));
            
            if (responseJson.containsKey("taskInfos")) {
                result.put("taskInfos", responseJson.get("taskInfos"));
            }
            
            return result;
            
        } catch (Exception e) {
            throw new Exception("获取冲突任务信息失败: " + e.getMessage(), e);
        }
    }
    
    /**
     * 处理冲突
     * 参考Go实现：ManageBatchTask
     */
    public void manageBatchTask(String taskType, String taskId, String targetFolderId, List<Map<String, Object>> taskInfos) throws Exception {
        try {
            String url = SignatureUtils.API_URL + "/batch/manageBatchTask.action";
            
            // 生成签名头
            String sessionKey = isFamily ? (String) tokenInfo.get("familySessionKey") : (String) tokenInfo.get("sessionKey");
            String sessionSecret = isFamily ? (String) tokenInfo.get("familySessionSecret") : (String) tokenInfo.get("sessionSecret");
            Map<String, String> headers = SignatureUtils.getSignatureHeader(url, "POST", sessionKey, sessionSecret);
            
            Map<String, Object> params = SignatureUtils.getClientSuffix();
            params.put("targetFolderId", targetFolderId);
            params.put("type", taskType);
            params.put("taskId", taskId);
            params.put("taskInfos", JSONUtil.toJsonStr(taskInfos));
            
            String response = HttpUtils.post(url, headers, params);
            JSONObject responseJson = HttpUtils.parseJsonResponse(response);
            
            if (HttpUtils.hasError(responseJson)) {
                throw new Exception("处理冲突失败: " + HttpUtils.getErrorMessage(responseJson));
            }
            
        } catch (Exception e) {
            throw new Exception("处理冲突失败: " + e.getMessage(), e);
        }
    }
}
